package com.yuns.util;

import javax.servlet.http.HttpServletRequest;
import java.util.*;


public class PayCommonUtil {

    // 随机字符串生成
    public static String getRandomString(int length) { // length表示生成字符串的长度
//        String base = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        String base = "0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }



    /**
     * @Date: 2018/6/6 11:08
     * @Descript: 因为公司app端与网页端商户号不一样，所以这里需要做一些判断
     */

    /* 微信公众号  */
    public static final String appid_wap = "your appid";
    public static final String MCHID_wap = "商户号";


    /**
     * 微信原生
     * appid 查看方法：登录微信商户平台（https://pay.weixin.qq.com/index.php/core/home/login） --> 营销中心 --> 支付后配置
     */
    public static final String appid = "your appid";
    public static final String MCHID = "商户号";
    public static final String notify_url = "你的通知接口地址";
    /**
     * 两个商户号的key又是一样的，这里就共用一个变量。
     * key 查看方法：登录微信商户平台 --> 账户中心 --> API安全 --> API密钥
     */
    public static final String key = "your key";


    /**
     * 创建微信交易对象
     */
    public static SortedMap<Object, Object> getWXPrePayID(String tradeType, String openid) {
        SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();

        Boolean isWap = false;
        Boolean isWx = false;
        if (StringUtil.notEmptyString(tradeType)) {
            if (tradeType.equals("JSAPI")) {
                //微信浏览器内执行
                isWx = true;
                isWap = true;
            }
            if (tradeType.equals("MWEB")) {
                //H5
                isWap = true;
            }
        }


        parameters.put("appid", isWap ? appid_wap : appid);
        parameters.put("mch_id", isWap ? MCHID_wap : MCHID);
        parameters.put("nonce_str", createNoncestr());
        parameters.put("fee_type", "CNY");
        parameters.put("notify_url", notify_url);
        parameters.put("trade_type", StringUtil.notEmptyString(tradeType) ? "APP" : tradeType);
        if (isWx) {
            //微信浏览器内执行需要openid
            parameters.put("openid", openid);
        }
        return parameters;
    }

    /**
     * 再次签名（仅APP支付需要）
     */
    public static SortedMap<Object, Object> startWXPay(Map map) {
        try {

            SortedMap<Object, Object> parameterMap = new TreeMap<Object, Object>();
            parameterMap.put("appid", appid);
            parameterMap.put("partnerid", MCHID);
            parameterMap.put("prepayid", map.get("prepay_id"));
            parameterMap.put("package", "Sign=WXPay");
            parameterMap.put("noncestr", createNoncestr());
            // 10位
            parameterMap.put("timestamp",
                    Long.parseLong(String.valueOf(System.currentTimeMillis()).toString().substring(0, 10)));
            String sign = PayCommonUtil.createSign("UTF-8", parameterMap);
            parameterMap.put("sign", sign);
            return parameterMap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /*
    * 获取真实IP
    * */
    public static String getRemortIP(HttpServletRequest request) {
        if (request.getHeader("x-forwarded-for") == null) {
            return request.getRemoteAddr();
        }
        return request.getHeader("x-forwarded-for");
    }

    /**
     * 创建随机数
     *16
     * @return
     */
    public static String createNoncestr() {
        String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        String res = "";
        for (int i = 0; i < 16; i++) {
            Random rd = new Random();
            res += chars.charAt(rd.nextInt(chars.length() - 1));
        }
        return res;
    }

    /**
     * @param characterEncoding 编码格式
     * @param parameters        请求参数
     * @return
     * @Description：创建sign签名
     */
    public static String createSign(String characterEncoding, Map<Object, Object> parameters) {
        StringBuffer sb = new StringBuffer();
        Set es = parameters.entrySet();
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            Object v = entry.getValue();
            if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }
        sb.append("key=" + key);
        String sign = MD5Utils.MD5Encode(sb.toString(), characterEncoding).toUpperCase();
        return sign;
    }

}
